package com.lenovo.testreport.user.controller;

import com.lenovo.session.LevelControl;
import com.lenovo.testreport.user.model.MessageCenter;
import com.lenovo.testreport.user.model.Userinfo;
import com.lenovo.testreport.user.service.RedisUserService;
import com.lenovo.testreport.user.service.MessageService;
import com.lenovo.testreport.user.service.UserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author CJF
 * @date 2018/10
 * <p>
 * 对用户表进行增查操作，用于用户登录、
 */
@Controller
@RequestMapping("/LoginAndRegister")
public class LoginAndRegister {
    @Autowired
    private UserService userService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private MessageService messageService;

    @Autowired
    private LevelControl LEVELCONTROL;

    @Autowired
    RedisUserService redisUserService;

    private RedisSerializer redisSerializer = new StringRedisSerializer();


    //用户登录
    @RequestMapping("/login")
    synchronized public String login(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView) {

        String name = request.getParameter("userEntity.userCode");
        String pwd = request.getParameter("userEntity.password");
        if (name != null && pwd != null) {
            Userinfo user = userService.findUserByName(name);
            if (user != null && user.getPassword().equals(pwd)) {
                request.getSession().setAttribute("User", name);
                request.getSession().setAttribute("level", user.getLevel());
                request.getSession().setAttribute("login_errormsg", null);
                redisTemplate.setKeySerializer(redisSerializer);
                String sessionId = "Lenovo-sessionId:" + request.getSession().getId();
                redisTemplate.opsForValue().set(sessionId, user, 5400, TimeUnit.SECONDS);
                redisUserService.addUser(user.getUid(), sessionId, request);
                Cookie IDCookie = new Cookie("Lenovo-sessionId", request.getSession().getId());

                IDCookie.setPath("/");
                IDCookie.setMaxAge(5400);
                response.addCookie(IDCookie);

                return "redirect:/index";
            } else {
                request.getSession().setAttribute("login_errormsg", "登录名或密码错误！");
                return "redirect:/login";
            }
        } else {
            request.getSession().setAttribute("login_errormsg", "用户名或密码不能为空！");
            return "redirect:/login";
        }
    }

    //用户登出
    @RequestMapping("/logout")
    synchronized public String logout(HttpServletRequest request) {
        request.getSession().setAttribute("User", "");
        request.getSession().setAttribute("level", "");
        String sessionId = request.getSession().getId();
        redisTemplate.delete("Lenovo-sessionId:" + sessionId);
        return "redirect:/login";
    }

    //用户注册
    // @RequestMapping("/register")
    synchronized public String register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("userEntity.userCode");
        String pwd = request.getParameter("userEntity.password");
        String email = request.getParameter("email");

        if (name == "" || pwd == "") {

            request.getSession().setAttribute("register_erromsg", "用户名或密码不能为空！");
            return "redirect:/register";
        }
        Userinfo user = userService.findUserByName(name);
        if (user != null) {
            request.getSession().setAttribute("register_erromsg", "用户名已存在！");
            return "redirect:/register";
        } else {
            Userinfo userinfo = new Userinfo();
            userinfo.setUsername(name);
            userinfo.setPassword(pwd);
            userinfo.setEmail(email);
            int result = userService.addUser(userinfo);
            if (result > 0) {
                Userinfo registeruser = userService.findUserByName(name);
                request.getSession().setAttribute("User", registeruser.getUsername());
                request.getSession().setAttribute("level", registeruser.getLevel());
                return "redirect:/index";
            } else {
                request.getSession().setAttribute("register_erromsg", "注册失败，请重试！");
                return "redirect:/register";
            }
        }
    }

    @RequestMapping("/register")
    synchronized public String register2(HttpServletRequest request, HttpServletResponse response) throws IOException {

        request.getSession().setAttribute("register_erromsg", "用户注册通道已关闭，请联系管理员开通账号！");
        return "redirect:/register";
    }

    @RequestMapping("/registerByAdmin")
    @ResponseBody
    synchronized public String registerByAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {

        if (!LEVELCONTROL.checkAdminSession(request)) {
            return "无此权限！";
        }

        String name = request.getParameter("username");
        String pwd = request.getParameter("password");
        String email = request.getParameter("email");

        Userinfo user = userService.findUserByName(name);
        if (user != null) {
            return "该用户已存在";
        } else {
            Userinfo userinfo = new Userinfo();
            userinfo.setUsername(name);
            userinfo.setPassword(pwd);
            userinfo.setEmail(email);
            int result = userService.addUser(userinfo);
            if (result > 0) {
                messageService.AddMessageRecord(new MessageCenter(request.getSession().getAttribute("User").toString(), "添加了新的用户：" + name, "user-admin"));
                return "注册成功!";
            } else {
                return "注册失败，请稍后重试!";
            }
        }

    }


}




